package io.renren.service.impl;

import cn.hutool.core.lang.UUID;
import io.renren.core.config.ProjectConStant;
import io.renren.dao.QrCodePaperDao;
import io.renren.entity.QrCodePaper;
import io.renren.service.QrCodePaperService;
import io.renren.utils.RRException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: hongyuliu
 * @Date: 2019-06-04
 * @Version 1.0
 */
@Service
@Slf4j
public class QrCodePaperServiceImpl implements QrCodePaperService {

    @Resource
    private QrCodePaperDao qrCodePaperDao;

    @Autowired
    private WxMpService wxMpService;

    @Override
    public QrCodePaper create() {
        // 获取没有使用的二维码
        QrCodePaper qrCodePaper = qrCodePaperDao.findOneByPaperUse();

        if (qrCodePaper == null) {
            qrCodePaperDao.updateBatch();
            qrCodePaper = qrCodePaperDao.findOneByPaperUse();
        }

        qrCodePaper.setPaperUse(1).setUpdateTime(new Date());
        // 更新为已用
        qrCodePaperDao.update(qrCodePaper.getId(), new Date());

        return qrCodePaper;
    }

    public QrCodePaper create1() {
        // 获取没有使用的二维码
        QrCodePaper qrCodePaper = qrCodePaperDao.findOneByPaperUse();

        if (qrCodePaper == null) {
            // 生成二维码
            qrCodePaper = new QrCodePaper();
            String qrCode = UUID.fastUUID().toString(true);
            String url = null;
            WxMpQrCodeTicket wxMpQrCodeTicket = null;
            try {
                // 获取永久二维码
                wxMpQrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateLastTicket(ProjectConStant.EXAM_PAPER_QR_CODE_PREFIX + qrCode);
                url = wxMpService.getQrcodeService().qrCodePictureUrl(wxMpQrCodeTicket.getTicket());
            } catch (WxErrorException e) {
                log.error("获取二维码错误");
                throw new RRException("服务端异常", 500);
            }
            qrCodePaper.setUrl(url);
            qrCodePaper.setState(0);
            qrCodePaper.setStyle(1);
            qrCodePaper.setPaperUse(1);
            qrCodePaper.setCode(qrCode);
            qrCodePaper.setCreateTime(new Date());
            qrCodePaper.setName("考试答题卡二维码");
            qrCodePaper.setDescription("考试答题卡二维码");
            qrCodePaper.setQrStr(wxMpQrCodeTicket.getUrl());
            qrCodePaperDao.save(qrCodePaper);
        } else {
            qrCodePaper.setPaperUse(1).setUpdateTime(new Date());
            // 更新为已用
            qrCodePaperDao.update(qrCodePaper.getId(), new Date());
        }

        return qrCodePaper;
    }
}
